#! /usr/bin/python
# -*- coding: cp1250 -*-

import re
import sys
import glob
import os
import string
import pepe.p_txt.bigtxt as bt
import pepe.p_filesystem.basic as pfb

import pepe.p_filesystem.dfstats as dfs

def srchMetricet(filename):
    ''' 
        import pepe.p_utils.oracle_dmp as odmp
        print odmp.srchMetricet(f)
        print odmp.srchMetricet(f)[9:]
    '''
    result = ''
    returned = False
    
    finfo = dfs.dfstats(filename, options=[])
    
    # if bigfile, skip first 99% of its size and search last 1%
    if finfo['size'] > 3000000:
    
        CHUNKSIZE = 20000000
        fi = open(filename, "rb")

        # go to the end of large file
        fi.seek(finfo['size'] - (finfo['size']/1000))
        bytes_read = fi.read(CHUNKSIZE)

        while bytes_read:
            n = re.search("(METRICET \d{1,})", bytes_read)
            if n:
                # take only first occurence
                if returned == False:
                    result = n.group(1)
                    returned = True
            bytes_read = fi.read(CHUNKSIZE)
        #finally:
        fi.close()

    else: # process small files
        
        for line in bt.lines(filename):
            if returned == True: break
            if re.search('METRICET ', line):
                # remove end of line characters
                line = re.sub('\x0D\x0A', '', line)
                line = re.sub('\x0D', '', line)
                line = re.sub('\x0A', '', line)
                # return only once, there are multiple 
                # METRICET strings in one dmp file
                if returned == False:
                    result = line
                    returned = True
                
    return result
    
def viaFileMask(filemask):
    ''' 
        oracle_dmp C:\\Rawdata\\abc.dmp
        oracle_dmp C:\\Rawdata\\*.dmp
        oracle_dmp *.dmp
    '''
    #fmask = string.split(pathfmask, '\x5C')[-1]
    #fpath = string.join(string.split(pathfmask, '\x5C')[:-1], '\x5C')

    # get list of files on given path, recursively
    #fl = pfb.fslist(root=fpath, patterns=fmask, recurse=True, return_folders=False)

    #o = open('oracle_dmp_output.dat#','wb')
    for f in glob.glob(filemask):
        result = srchMetricet(f)
        print "%s\t%s\t%s" % (f, result[9:], result)
        #o.write("%s\t%s\t%s\x0D\x0A" % (f, result[9:], result))
    #o.close()

if __name__ == '__main__':
    ''' '''
    if len(sys.argv) == 2:
        viaFileMask(sys.argv[1])
    else:
        print viaFileMask.__doc__
